package com.fancy.learncenter.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonAnswerKeysBean;
import com.fancy.learncenter.bean.CartoonAnswersBean;
import com.fancy.learncenter.bean.CartoonCommitAnswerBean;
import com.fancy.learncenter.bean.CartoonGetAnswerResultBean;
import com.fancy.learncenter.bean.CartoonGetHomeAnswerBean;
import com.fancy.learncenter.bean.CartoonMediaBean;
import com.fancy.learncenter.bean.CartoonOptionsBean;
import com.fancy.learncenter.bean.CartoonStemsBean;
import com.fancy.learncenter.bean.CartoonTextsBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.adapter.CartoonQuestionTextOptionAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.ui.view.CartoonAnalysisPopu;
import com.fancy.learncenter.utils.CartoonToastUtils;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.common.JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_ANALYSIS;
import static com.fancy.learncenter.common.JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_LIGHT;
import static com.fancy.learncenter.common.JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
import static com.fancy.learncenter.common.JumpIntentKey.RIGHT_NUM;

/**
 * 语法习题-----看图选择（选句子）
 */
public class GrammarSeeImageChooseFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.commit_image)
    ImageView commitImage;
    @Bind(R.id.image)
    SimpleDraweeView image;
    @Bind(R.id.question_name)
    TextView questionName;
    @Bind(R.id.previous_question)
    ImageView previousQuestion;
    @Bind(R.id.next_question)
    ImageView nextQuestion;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    // TODO: Rename and change types of parameters
    private int currentIndex;
    private int totalNum;
    ArrayList<QuestionVOsBean> questionList;
    private OnSeeImageChooseListener mListener;
    private List<CartoonTextsBean> optionList = new ArrayList<>();
    private String standardAnswer;
    private String writeAnswer;
    private String titleStr;
    private JumpIntentKey.QUESTION_ENTER_TYPE type;
    private String homePackageId;
    private Handler handler = new Handler();
    private QuestionVOsBean questionVOsBean;
    private int state;
    private List<CartoonCommitAnswerBean> commitAnswerBeanList;
    private String studentHomeworkId;
    private CartoonQuestionTextOptionAdapter optionAdapter;
    private JumpIntentKey.CARTOON_BUTTON_STATUS buttonStatus;
    private String analysisText;
    private Fragment currentFragment;
    private String lessonNameStr;
    private String unitNameStr;
    public GrammarSeeImageChooseFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment GrammarSeeImageChooseFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GrammarSeeImageChooseFragment newInstance(ArrayList<QuestionVOsBean> list, int currentIndex, int totalNum, JumpIntentKey.QUESTION_ENTER_TYPE type,
                                                            String homePackageId, String studentHomeworkId, String lessonNameStr,String unitNameStr) {
        GrammarSeeImageChooseFragment fragment = new GrammarSeeImageChooseFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, list);
        args.putInt(ARG_PARAM1, currentIndex);
        args.putInt(ARG_PARAM2, totalNum);
        args.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
        args.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
        args.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
        args.putString(JumpIntentKey.LESSON_NAME,lessonNameStr);
        args.putString(JumpIntentKey.UNIT_NAME,unitNameStr);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentFragment = this;
        if (getArguments() != null) {
            currentIndex = getArguments().getInt(ARG_PARAM1);
            totalNum = getArguments().getInt(ARG_PARAM2);
            type = (JumpIntentKey.QUESTION_ENTER_TYPE) getArguments().getSerializable(JumpIntentKey.QUESTION_ENTER);
            questionList = getArguments().getParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY);
            homePackageId = getArguments().getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);
            studentHomeworkId = getArguments().getString(JumpIntentKey.STUDENTHOMEWORKID);
            lessonNameStr = getArguments().getString(JumpIntentKey.LESSON_NAME);
            unitNameStr = getArguments().getString(JumpIntentKey.UNIT_NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_see_image_choose, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView();
        return view;
    }


    private void initView() {

        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
            case DO_IT_AGAIN:
                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;

            case HAS_CORRECTED:
            case NOT_CORRECTED:
            case ERROR_KINDS:
                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                break;

            case WORK_REPORT:
                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                getWorkReportAnswer();
                break;

            case TEACHER_WORK_PREVIEW:
                seeAnswer();
                break;

        }

        Utils.notifyButtonBg(buttonStatus,commitImage);

        commitImage.setEnabled(false);
        commitImage.setOnClickListener(this);
        previousQuestion.setOnClickListener(this);
        nextQuestion.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        optionAdapter = new CartoonQuestionTextOptionAdapter(getContext(), type, optionList);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(optionAdapter);

        optionAdapter.setListener(new AlbumImpl() {
            @Override
            public void onClick(int position) {

                for (int i = 0; i < optionList.size(); i++) {
                    if (i != position) {
                        optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT);
                    } else {
                        optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_CHOOSE);
                    }
                }

                buttonStatus = STATUS_LIGHT;
                Utils.notifyButtonBg(buttonStatus,commitImage);
                writeAnswer = optionList.get(position).getValue();
                optionAdapter.notifyDataSetChanged();
            }
        });

    }

    private void initData() {


        questionVOsBean = questionList.get(currentIndex);
        if (questionVOsBean != null) {
            CartoonAnswerKeysBean answerKeysBean = questionVOsBean.getAnswerKeys();
            if (answerKeysBean != null) {
                List<CartoonTextsBean> answerKeysList = answerKeysBean.getTexts();
                if (answerKeysList != null && answerKeysList.size() > 0){

                    analysisText =  answerKeysList.get(0).getValue();
                }
            }
            CartoonStemsBean stemsBean = questionVOsBean.getStems();
            List<CartoonMediaBean> imageList = stemsBean.getImages();
            List<CartoonTextsBean> textsList = stemsBean.getTexts();
            if (imageList != null && imageList.size() > 0) {
                image.setVisibility(View.VISIBLE);
                image.setImageURI(imageList.get(0).getImgUrl());
            } else {
                image.setVisibility(View.GONE);
            }
            if (textsList != null && textsList.size() > 0) {
                questionName.setText(textsList.get(0).getValue());
            }

            CartoonOptionsBean optionsBean = questionVOsBean.getOptions();
            optionList.addAll(optionsBean.getTexts());
            for (CartoonTextsBean bean: optionList){
                bean.setStatus(JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT);
            }
            CartoonAnswersBean answersBean = questionVOsBean.getAnswers();
            standardAnswer = answersBean.getTexts().get(0).getValue();
            titleStr = questionVOsBean.getConstructionNameCn();
            onButtonPressed(currentIndex + 1, totalNum, titleStr);
        }
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(int currentIndex, int totalNum, String titleStr) {
        if (mListener != null) {
            mListener.onSeeImageChoose(currentIndex, totalNum, titleStr);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnSeeImageChooseListener) {
            mListener = (OnSeeImageChooseListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commit_image:
                switch (buttonStatus) {
                    case STATUS_LIGHT:

                        judgeRightOrWrong();
                        switch (type) {
                            case DO_WORK:
                            case CONTINUE_WORK:
                            case DO_IT_AGAIN:
                            case HAS_CORRECTED:
                                commitAnswers();
                                break;
                            case NOT_CORRECTED:
                            case ERROR_KINDS:
                                if (state == 1) {
                                    errorQuestionCommitAnswer();
                                }else {
                                    errorBusniessLogic();
                                }
                                break;
                        }
                        break;
                    case STATUS_SEE_ANSWER:
                        seeAnswer();
                        break;
                    case STATUS_ANALYSIS:
                        CartoonAnalysisPopu popu = new CartoonAnalysisPopu(getActivity(),analysisText,commitImage);
                        popu.showPopupWindow();
                        break;


                }
                break;
            case R.id.previous_question:
                returnToOriginal();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction, questionList, currentIndex - 1, R.id.fg_container, type,
                        homePackageId, studentHomeworkId,lessonNameStr,unitNameStr);
                break;
            case R.id.next_question:
                returnToOriginal();
                FragmentTransaction transaction2 = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction2, questionList, currentIndex + 1, R.id.fg_container,
                        type, homePackageId, studentHomeworkId,lessonNameStr,unitNameStr);

                break;

        }
    }

    /**
     * 查看答案
     */
    private void seeAnswer(){

        for (int i = 0; i < optionList.size(); i++){

            if (standardAnswer.equals(optionList.get(i).getValue())){

                optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_RIGHT);
            }
        }
        buttonStatus = STATUS_ANALYSIS;
        optionAdapter.notifyDataSetChanged();
        Utils.notifyButtonBg(buttonStatus,image);

    }

    /**
     * 获取客观题答案
     */
    private void getWorkReportAnswer() {

        Map<String, Object> map = new HashMap<>();
        map.put("packageId", homePackageId);
        map.put("classId", MyApplication.classIDStr);
        map.put("questionId", questionVOsBean.getQuestionId());

        HttpMehtod.getInstance().cartoonGetHomeAnswer(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonGetAnswerResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonGetAnswerResultBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonGetAnswerResultBean>() {
                    @Override
                    public void success(CartoonGetAnswerResultBean dataBean) {

                        if (dataBean != null) {
                            CartoonGetHomeAnswerBean homeAnswerBean = dataBean.getResult();
                            List<CartoonCommitAnswerBean> answerResourceList = homeAnswerBean.getAnswerResourceList();
                            String answerId = "";
                            if (answerResourceList != null && answerResourceList.size() > 0) {
                                answerId = answerResourceList.get(0).getQuestionResourceId();
                            }

                            for (int i = 0; i < optionList.size(); i++){

                                if (String.valueOf(optionList.get(i).getId()).equals(answerId)){
                                    String value = optionList.get(i).getValue();
                                    if (standardAnswer.equals(value)) {
                                        optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_RIGHT);
                                        commitImage.setVisibility(View.INVISIBLE);
                                    }else {
                                        commitImage.setVisibility(View.VISIBLE);
                                        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                                        optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_WRONG);
                                        Utils.notifyButtonBg(buttonStatus,commitImage);
                                    }
                                }else {
                                    optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT);
                                }

                            }


                            optionAdapter.notifyDataSetChanged();



                        }

                    }

                    @Override
                    public void fail(String errorCode) {


                    }
                }).dealData();
            }
        });

    }



    private void judgeRightOrWrong() {

        if (standardAnswer.equals(writeAnswer)) {
            RIGHT_NUM ++;
            state = 1;
            CartoonToastUtils.show(true);
        } else {
            state = 0;
            CartoonToastUtils.show(false);
        }
    }

    private void commitAnswers() {
        commitAnswerBeanList = new ArrayList<>();
        CartoonCommitAnswerBean answerBean = new CartoonCommitAnswerBean();
        answerBean.setResourceValue(writeAnswer);
        answerBean.setResourceType("0");
        commitAnswerBeanList.add(answerBean);
        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("state", state);
        map.put("homeworkPackageId", homePackageId);
        map.put("objectQuestionId", questionVOsBean.getQuestionId());
        map.put("answerResourceList", commitAnswerBeanList);
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonCommitHomeAnsers(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                switch (type) {

                    case HAS_CORRECTED:
                    case NOT_CORRECTED:
                    case ERROR_KINDS:
                        if (state == 1) {
                            jumpToQuestion(currentIndex + 1);
                        } else {
                            errorBusniessLogic();
                        }
                        break;

                    case DO_WORK:
                    case DO_IT_AGAIN:
                    case CONTINUE_WORK:
                       jumpToQuestion(currentIndex + 1);

                        break;

                }

            }
        });
    }

    /**
     * 错题中心 -- 未订正 错题分类
     */
    private void errorQuestionCommitAnswer() {
        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkDoneDetailId", questionVOsBean.getStudentHomeworkDoneDetailId());
        HttpMehtod.getInstance().cartoonCorrectErrorQuestion(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                jumpToQuestion(currentIndex + 1);

            }
        });
    }

    private void errorBusniessLogic(){

        for (int i = 0; i < optionList.size(); i++) {

            if (optionList.get(i).getStatus() == JumpIntentKey.OPTION_STATUS.STATUS_CHOOSE) {
                optionList.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_WRONG);
                break;
            }
        }
        type = JumpIntentKey.QUESTION_ENTER_TYPE.NO_CLICK;
        buttonStatus = STATUS_SEE_ANSWER;
        Utils.notifyButtonBg(buttonStatus,commitImage);
        optionAdapter.notifyDataSetChanged();
    }


    private void jumpToQuestion(final int index){
        returnToOriginal();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                Utils.switchFragment(getActivity(), transaction, questionList, index, R.id.fg_container,
                        type, homePackageId, studentHomeworkId,lessonNameStr,unitNameStr);
            }
        }, 1500);
    }

    private void returnToOriginal(){

        for (CartoonTextsBean bean: optionList){
            bean.setStatus(null);
        }

    }


    /**
     *
     */
    public interface OnSeeImageChooseListener {
        // TODO: Update argument type and name
        void onSeeImageChoose(int currentIndex, int totalNum, String title);
    }
}
